// 公用倒计时
var timer = null

// 清除倒计时
function clearTimer () {
  clearTimeout(timer)
}

// 毫秒级倒计时
function countDown (that, totalMicroSecond) {
  if (totalMicroSecond <= 0) {
    that.send = true
    that.message = '重新发送验证码'
    // timeout则跳出递归
    return
  }

  // 渲染倒计时时钟
  that.message = dateFormat(totalMicroSecond) + ' 秒'

  timer = setTimeout(function () {
    totalMicroSecond -= 10
    countDown(that, totalMicroSecond)
  }, 10)
}

// 时间格式化输出，如03:25:19 86。每10ms都会调用一次
function dateFormat (microSecond) {
  // 秒数
  var second = Math.floor(microSecond / 1000)
  // 小时位
  var hr = Math.floor(second / 3600)
  // 分钟位
  var min = fillZeroPrefix(Math.floor((second - hr * 3600) / 60))
  // 秒位
  var sec = fillZeroPrefix((second - hr * 3600 - min * 60)) // equal to => var sec = second % 60;

  return sec
}

// 位数不足补零
function fillZeroPrefix (num) {
  return num < 10 ? '0' + num : num
}

module.exports.countDown = countDown
module.exports.clearTimer = clearTimer
